package bigdata.monitor.binlog.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;

public class CanalToDebeziumConverter {

    public static String convert(String canalJson) {
        JSONObject data = JSON.parseObject(canalJson);

        String database = data.getString("database");
        String table = data.getString("table");
        String type = data.getString("type");

        String op;
        if ("UPDATE".equals(type)) {
            op = "u";
        } else if ("INSERT".equals(type)) {
            op = "c";
        } else if ("DELETE".equals(type)) {
            op = "d";
        } else {
            return "{}";
        }

        Long ts = data.getLong("ts");

        // 构建 source
        JSONObject source = new JSONObject();
        source.put("version", "2.4.0.Final");
        source.put("connector", "TiCDC");
        source.put("name", "default");
        source.put("ts_ms", ts);
        source.put("snapshot", "false");
        source.put("db", database);
        source.put("schema", database);
        source.put("table", table);
        source.put("server_id", 0);
        source.put("gtid", null); // 直接放 null
        source.put("file", "");
        source.put("pos", 0);
        source.put("row", 0);
        source.put("thread", 0);
        source.put("query", null);

        // 构建 before / after
        JSONArray newArr = data.getJSONArray("data");
        JSONArray oldArr = data.getJSONArray("old");

        JSONObject oldData = null;
        JSONObject newData = null;

        if ("c".equals(op)) {
            newData = (newArr != null && !newArr.isEmpty()) ? newArr.getJSONObject(0) : null;
        } else if ("u".equals(op)) {
            oldData = (oldArr != null && !oldArr.isEmpty()) ? oldArr.getJSONObject(0) : null;
            newData = (newArr != null && !newArr.isEmpty()) ? newArr.getJSONObject(0) : null;
        } else if ("d".equals(op)) {
            oldData = (newArr != null && !newArr.isEmpty()) ? newArr.getJSONObject(0) : null;
        }

        // 组装
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("source", source);
        jsonObj.put("before", oldData);   // 可能为 null
        jsonObj.put("after", newData);    // 可能为 null
        jsonObj.put("op", op);
        jsonObj.put("ts_ms", ts);
        jsonObj.put("transaction", null);
        return jsonObj.toJSONString(JSONWriter.Feature.WriteMapNullValue);
    }
}
